package com.taimi.springbootzendaodemo;

import java.awt.AWTPermission;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.Locale;

import com.taimi.springbootzendaodemo.edition.GetEditionInfo;
import com.taimi.springbootzendaodemo.edition.VersionInfo;
import com.taimi.springbootzendaodemo.mail.MailTemplate;
import com.taimi.springbootzendaodemo.mail.TaimiMailSender;
import com.taimi.springbootzendaodemo.system.TemplateProperties;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.FileTemplateResolver;

import lombok.extern.slf4j.Slf4j;

@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
@Slf4j
public class ZendaoMailApplication {

	public static final String LINE_SEPARATOR = System.getProperty("line.separator");

	public static void main(String[] args) {		
		new SpringApplicationBuilder(ZendaoMailApplication.class).headless(false).run(args);
	}

	@Autowired
	private GetEditionInfo getEditinInfo;

	@Autowired
	private TaimiMailSender mailSender;

	@Autowired
	private TemplateProperties templateProperties;

	@Bean
	public CommandLineRunner executeSendMail() {
		return args -> {
			String address = "";
			if (args.length == 0 || StringUtils.isEmpty(args[0])) {
				log.info("版本地址参数为空，将从剪切板中获取");
				String textFromClipboard = getTextFromClipboard();
				address = textFromClipboard;
				log.info("版本地址：{}", address);
			} else {
				address = args[0];
			}
			VersionInfo versionInfo = getEditinInfo.getVersionInfo(address);
			FileTemplateResolver fileTemplateResolver = new FileTemplateResolver();
			fileTemplateResolver.setCharacterEncoding("utf8");
			fileTemplateResolver.setTemplateMode(TemplateMode.HTML);
			SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
			springTemplateEngine.setTemplateResolver(fileTemplateResolver);
			Context context = new Context(Locale.SIMPLIFIED_CHINESE);
			versionInfo.setAddress(address);
			context.setVariable("versionInfo", versionInfo);
			String template = springTemplateEngine.process(templateProperties.getTemplate(), context);
			log.info("{}rendered template:{} {}", LINE_SEPARATOR, LINE_SEPARATOR, template);
			MailTemplate mailTemplate = MailTemplate.builder().subject(versionInfo.getBuildInfo().getName())
					.to(templateProperties.getTo()).cc(templateProperties.getCc()).template(template)
					.from_(templateProperties.getFrom()).build();
			mailSender.sendMail(mailTemplate);
		};
	}

	private String getTextFromClipboard() throws UnsupportedFlavorException, IOException {
		SecurityManager securityManager = System.getSecurityManager();
		if (securityManager != null) {
			Object securityContext = securityManager.getSecurityContext();
			securityManager.checkPermission(new AWTPermission("accessClipboard"), securityContext);
		}
		Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
		Transferable content = clipboard.getContents(null);
		if (content.isDataFlavorSupported(DataFlavor.stringFlavor)) {
			String text = (String) clipboard.getData(DataFlavor.stringFlavor);
			// 剪切板没有内容就别回应了
			if (text != null && text.length() > 0) {
				return text;

			}
		}
		return "";
	}
}
